package com.basker.pisces.auth.facade;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.basker.pisces.auth.domain.exception.AuthUserRegisteredException;
import com.basker.pisces.auth.domain.service.IAuthDomainService;
import com.basker.pisces.auth.service.api.IAuthService;
import com.basker.pisces.auth.service.pojo.ChangePasswordRequest;
import com.basker.pisces.auth.service.pojo.LoginRequest;
import com.basker.pisces.auth.service.pojo.LoginResult;
import com.basker.pisces.auth.service.pojo.RegistRequest;
import com.basker.pisces.context.LoginContext;
import com.basker.pisces.resource.StringResources;
import com.basker.pisces.service.dto.DefaultServiceResult;
import com.basker.pisces.service.dto.ServiceResultFactory;
import com.basker.pisces.springcloud.utils.RequestUtils;

@RestController
public class AuthServiceRestController implements IAuthService {

    @Autowired
    private IAuthDomainService authDomainService;

    @Override
    public DefaultServiceResult<Void> changePassword(@RequestBody @Valid ChangePasswordRequest request) {
        this.authDomainService.changePassword(request);
        return ServiceResultFactory.ok(StringResources.get("pisces-auth-service.changePassword-ok"));
    }

    @Override
    public DefaultServiceResult<LoginContext> identify() {
        String tokenId = RequestUtils.getHeader(IAuthService.TOKEN_ID_KEY, true);
        LoginContext lcx = this.authDomainService.identify(tokenId);

        if (lcx != null) {
            return ServiceResultFactory.ok(StringResources.get("pisces-auth-service.identify-ok"), lcx);
        } else {
            return ServiceResultFactory.error(IAuthService.INVALID_TOKEN_STATUS,
                    StringResources.get("pisces-auth-service.identify-error-001"));
        }
    }

    @Override
    public DefaultServiceResult<LoginResult> login(@RequestBody @Valid LoginRequest request) {
        LoginResult result = authDomainService.login(request);
        return ServiceResultFactory.ok(StringResources.get("pisces-auth-service.login-ok"), result);
    }

    @Override
    public DefaultServiceResult<Void> logout() {
        String tokenId = RequestUtils.getHeader(IAuthService.TOKEN_ID_KEY, true);
        this.authDomainService.logout(tokenId);

        return ServiceResultFactory.ok(StringResources.get("pisces-auth-service.logout-ok"));
    }

    @Override
    public DefaultServiceResult<Long> regist(@RequestBody @Valid RegistRequest request) {
        try {
            Long authUserId = this.authDomainService.regist(request);
            return ServiceResultFactory.ok(StringResources.get("pisces-auth-service.regist-ok"), authUserId);
        } catch (AuthUserRegisteredException e) {
            return ServiceResultFactory.error(IAuthService.ALREADY_REGISTED, e.getMessage());
        }

    }

}
